package org.beaconframework.util.expression;

import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.beaconframework.util.xml.XPathResolverRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XpathExpressionEngine implements ExpressionEngine {
    private static Logger engineLog = LoggerFactory
            .getLogger(XpathExpressionEngine.class);

    @Override
    public Object evaluate(String expression, Map<String, Object> vars) {
        return evaluate(expression, vars, XPathConstants.STRING);
    }

    public Object evaluate(String expression, Map<String, Object> vars,
            QName returnType) {
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();

            XPathResolverRegistry vr = (XPathResolverRegistry) vars
                    .get(XPathResolverRegistry.class.getName());
            if (vr != null) {

                vr.attach(xpath);
            }
            XPathExpression xpr = xpath.compile(expression);

            Object output = xpr.evaluate(vars
                    .get(ExpressionEngine.ROOT_VARIABLE_NAME), returnType);

            if (engineLog.isDebugEnabled()) {
                engineLog.debug("xpath '{}' => '{}'", expression, output);
            }
            return output;
        } catch (XPathExpressionException e) {
            if (engineLog.isWarnEnabled()) {
                engineLog.error("error with expression '" + expression + "'");

            }
            throw new ExpressionEvaluationException(e);
        }
    }
}
